//
//  LoginViewController.m
//  Conference
//
//  Created by Xiang He on 12-11-14.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "MainViewController.h"
#import "Constant.h"
#import "Globals.h"
#import "MD5Tool.h"
#import "WebData.h"
#import "NetContant.h"
#import "Member.h"
#import "AppDelegate.h"
#import "MainDataBase.h"
#import "Globals.h"
#import "AccountCellController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

@synthesize userBg;
@synthesize pasBg;
@synthesize txt_user_name=_txt_user_name;
@synthesize txt_password=_txt_password;
@synthesize chk_autologin;
@synthesize chk_rempwd;
@synthesize tableview;
@synthesize popView;
@synthesize userName;
@synthesize passWord;
@synthesize memberList;

@synthesize isFromLogout;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        IS_FROM_LOGOUT=false;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    [self.popView setBackgroundColor:[UIColor clearColor]];
    
    UIImage *loginUserBG=[[UIImage imageNamed:@"login_input_accout.png"]stretchableImageWithLeftCapWidth:19 topCapHeight:34
    ];  
    UIImage *loginPassBG=[[UIImage imageNamed:@"login_input_pwd.png"]stretchableImageWithLeftCapWidth:19 topCapHeight:34
                          ];  
    [self.userBg setImage:loginUserBG];
    [self.pasBg setImage:loginPassBG];
    
//    [self.txt_user_name setBackground:loginUserBG];
//    [self.txt_password setBackground:loginPassBG];
    
    
//    UILabel  *paddingView = [[UILabel  alloc] initWithFrame:CGRectMake(0, 0, 10, 25)];
//    paddingView.text  = @"";
//    paddingView.textColor  = [UIColor  darkGrayColor];
//    paddingView.backgroundColor  = [UIColor  clearColor];
//    
//    self.txt_user_name.leftView  = paddingView;
//    self.txt_user_name.leftViewMode  = UITextFieldViewModeAlways;
//    
//    self.txt_password.leftView  = paddingView;
//    self.txt_password.leftViewMode  = UITextFieldViewModeAlways;
//    
//    [paddingView release];
    
    self.tableview.backgroundView=[[[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"contact_change_popup_window_bg.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:18]] autorelease];
    

    if([[NSUserDefaults standardUserDefaults] boolForKey:[[Constant getInstance] AutoLogin]]){
        
        
        [self login];
    
   }
    
}


-(void)viewWillAppear:(BOOL)animated{
    
   [self initData];

   [self loadingViewData];
    
}

-(void)initData{
    
    
    self.memberList=[[MainDataBase getInstance] getUserName];

}

-(void)loadingViewData{

    [self.txt_user_name setText:[[NSUserDefaults standardUserDefaults] objectForKey:[[Constant getInstance] userName]]];

    if ([[NSUserDefaults standardUserDefaults] boolForKey:[[Constant getInstance] ChgPwd]]) {
        [self.txt_password setText:[[NSUserDefaults standardUserDefaults] objectForKey:[[Constant getInstance] Pwd]]];
        [self.chk_rempwd setSelected:YES];
    }else {
        [self.txt_password setText:@""];
         [self.chk_rempwd setSelected:NO];
    }
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:[[Constant getInstance] AutoLogin]]) {
            
        [self.chk_autologin setSelected:YES];
    }
}

-(void)login{
    
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] setUserMember:[[MainDataBase getInstance] getAutoMember]];

    MainViewController *mainView=[[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
    [self.navigationController pushViewController:mainView animated:YES];
    [mainView release];
    
}


-(void)run{
    
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    
    NSString *sRet=[[WebData getInstance] userCheckVersion:self.userName pwd:[MD5Tool MD5:self.passWord]];
    
    [self performSelectorOnMainThread:@selector(onPostExecute:) withObject:sRet waitUntilDone:YES];
    [pool release];
    
}


-(void)onPostExecute:(NSString *)sRet{
    
    [[[Globals getInstance] progress_view] removeFromSuperview];
    
    if ([sRet isEqualToString:[[NetContant getInstance] NET_CONNECT_FALSE]]) {
        
      
        [[Globals getInstance] showAlertView:[[Constant getInstance] net_error]];
        
        
    }else if([sRet isEqualToString:[[NetContant getInstance] NETWORK_RECORD_ISEMPTY]]){
    
         [[Globals getInstance] showAlertView:[[Constant getInstance] account_error]];
        
    }else {
        
        @try {
            
            [self doNetRet:sRet];
            [self doNetInfo];
            
        }
        @catch (NSException *exception) {
            
             [[Globals getInstance] showAlertView:[[Constant getInstance] net_error]];
            
        }
    
    }
  
}

-(void)doNetRet:(NSString *)sRet{
    
    Member *userInfo =[[Member alloc] init];
    
    NSArray *arrayOfInfo =[sRet componentsSeparatedByString:[[NetContant getInstance] RECORDS_SPLIT_FLAG]];
    
    [userInfo setMemberId:[[arrayOfInfo objectAtIndex:0] intValue]];
    [userInfo setFirstName:[arrayOfInfo objectAtIndex:1]];
    [userInfo setLastName:[arrayOfInfo objectAtIndex:2]];
    if (![@"True" isEqualToString:[arrayOfInfo objectAtIndex:3]]) {
         [userInfo setGender:NO];
    }else {
         [userInfo setGender:YES];
    }
    [userInfo setCompanyName:[arrayOfInfo objectAtIndex:4]];
    [userInfo setConferenceId:[[arrayOfInfo objectAtIndex:5] intValue]];
    [userInfo setMobile:[arrayOfInfo objectAtIndex:6]];
    [userInfo setPhone:[arrayOfInfo objectAtIndex:7]];
//    [userInfo setBarcode:[arrayOfInfo objectAtIndex:8]];
    [[NSUserDefaults standardUserDefaults] setObject:self.userName forKey: [[Constant getInstance] userName]];
    [[NSUserDefaults standardUserDefaults] setObject:self.passWord forKey: [[Constant getInstance] Pwd]];
    [userInfo setUserName:self.userName];
    [userInfo setPwd:self.passWord];
    [[NSUserDefaults standardUserDefaults] setObject:[arrayOfInfo objectAtIndex:8] forKey: [[Constant getInstance] MeetingName]];
    
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] setUserMember:userInfo];
    
    [[MainDataBase getInstance] addUser:userInfo];
    
    [userInfo release];
    
}

-(void) doNetInfo{

   
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:chk_autologin.isSelected] forKey:[[Constant getInstance] AutoLogin]];
    
     [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:chk_rempwd.isSelected] forKey:[[Constant getInstance] ChgPwd]];
    
     MainViewController *mainView=[[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
    [self.navigationController pushViewController:mainView animated:YES];
    [mainView release];
    
    
}

- (void)viewDidUnload
{
    
    [self setTxt_user_name:nil];
    [self setTxt_password:nil];
    [self setUserName:nil];
    [self setPassWord:nil];
    
    [self setChk_autologin:nil];
    [self setChk_rempwd:nil];
    [self setMemberList:nil];
    [self setTableview:nil];
    [self setPopView:nil];
    [self setUserBg:nil];
    [self setPasBg:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    
    [_txt_user_name release];
    [_txt_password release];
        
    [userName release];
    [passWord release];
    
    [chk_autologin release];
    [chk_rempwd release];
    [memberList release];

    [tableview release];
    [popView release];
    [userBg release];
    [pasBg release];
    [super dealloc];
}

- (IBAction)loginAction:(id)sender {
    
    self.userName=_txt_user_name.text;
    self.passWord=_txt_password.text;
    
    if ([_txt_user_name.text isEqualToString:@""]) {
        
        [[Globals getInstance] showAlertView:[[Constant getInstance] username_isempty]];
        
        [_txt_user_name becomeFirstResponder];
        
        return;
    }
    
    if ([_txt_password.text isEqualToString:@""]) {
        
        [[Globals getInstance] showAlertView:[[Constant getInstance] pwd_isempty]];
        
        [_txt_password becomeFirstResponder];
        
        return;
    }
    
    [_txt_password resignFirstResponder];
    [_txt_user_name resignFirstResponder];
    [self.view addSubview:[[Globals getInstance] progress_view]];
    
    NSThread *thread=[[[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil] autorelease];
    
    [thread start];

    
}

- (IBAction)autoLoginAction:(id)sender {
    

      
    [chk_autologin setSelected:!chk_autologin.isSelected];
     
    
}

- (IBAction)remPwdAction:(id)sender {
    
    [chk_rempwd setSelected:!chk_rempwd.isSelected];
    
}

- (IBAction)dropDownAction:(id)sender {
    
    
    
    
    [self showMoreAccount ];
    
    
}


-(void)showMoreAccount{

    if(self.memberList==nil || [self.memberList count]==0)
        return;
    
    [self.tableview reloadData];
    
    int x=self.tableview.frame.origin.x;
       int y=self.tableview.frame.origin.y;
    int width=self.tableview.frame.size.width;
    
    int oldheight=self.memberList.count*accountCellHeight+15;
    int height=oldheight>145?145:oldheight;
    
    [self.tableview setFrame:CGRectMake(x, y, width,height)];
    
    [self.view  addSubview:self.popView];

}


- (IBAction)nextOrDoneAction:(id)sender {
    
    if(sender==_txt_user_name)
        [_txt_password becomeFirstResponder];
    
    if (sender==_txt_password) {
        [_txt_password resignFirstResponder];
    }
}

- (IBAction)hidePopView:(id)sender {
    
    [self.popView removeFromSuperview];
}

-(void)deleteSurfingCcUser:(id)sender{

    UIButton *btn=(UIButton*)sender;
    [[MainDataBase getInstance] DelUser:[self.memberList objectAtIndex:btn.tag]];
    [self.memberList removeObjectAtIndex:btn.tag];
    [self.tableview reloadData];
    if([self.memberList count]==0){
        [self.popView removeFromSuperview];
    }
        

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return accountCellHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.memberList count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *accountCell=@"accountCell";
    AccountCellController *cell=(AccountCellController *)[tableView dequeueReusableCellWithIdentifier:accountCell];
    if(cell ==nil){
		NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"AccountCellController" owner:self options:nil];
		for (id oneObject in array) {
			if ([oneObject isKindOfClass:[AccountCellController class]]) {
				cell=oneObject;
				break;
			}
		}
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    
    int row=[indexPath row];
    Member *account = [self.memberList objectAtIndex:row];
    
    cell.label_userName.text=account.userName;
    
    [cell.btn_del setTag:row];
    [cell.btn_del addTarget:self action:@selector(deleteSurfingCcUser:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    Member *account=[self.memberList objectAtIndex:[indexPath row]];
    
    
    [self showAccountAndPswToUi:account];
    [self.popView removeFromSuperview];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

-(void)showAccountAndPswToUi:(Member*)user{

    [self.txt_user_name setText:user.userName];

}


@end
